package routing;

import com.rabbitmq.client.*;
import constant.Constants;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

public class Consumer1 {
    public static void main(String[] args) throws IOException, TimeoutException {
        // 创建连接工厂
        ConnectionFactory factory = new ConnectionFactory();
        // 设置IP地址、端口号
        factory.setHost(Constants.HOST);
        factory.setPort(Constants.PORT);
        // 设置虚拟机名称
        factory.setVirtualHost(Constants.VIRTUAL_HOST);
        // 设置用户名和密码
        factory.setUsername(Constants.USER_NAME);
        factory.setPassword(Constants.USER_PASSWORD);
        // 创建连接
        Connection connection = factory.newConnection();
        // 建立 channel
        Channel channel = connection.createChannel();
        // 声明队列
        channel.queueDeclare(Constants.ROUTINT_QUEUE_1, true, false, false, null);
        // 消费消息
        DefaultConsumer consumer = new DefaultConsumer(channel) {
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                System.out.println("接收到消息: " + new String(body));
            }
        };
        channel.basicConsume(Constants.ROUTINT_QUEUE_1, true, consumer);
        // 释放资源
//        channel.close();
//        connection.close();
    }
}
